<template>
  <div>
    <el-select v-model="value" placeholder="入住状态" style="margin-left: 10px">
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      >
      </el-option>
    </el-select>
    <el-input
      v-model="input"
      placeholder="单元名称"
      style="width: 200px; margin-left: 10px"
    ></el-input>
    <el-input
      v-model="input1"
      placeholder="幢号"
      style="width: 200px; margin-left: 10px"
    ></el-input>
    <el-input
      v-model="input2"
      placeholder="房号"
      style="width: 200px; margin-left: 10px"
    ></el-input>
    <el-input
      v-model="name"
      placeholder="住客姓名"
      style="width: 200px; margin-left: 10px"
    ></el-input>
    <el-button type="primary" icon="el-icon-search" style="margin-left: 10px" @click="search"
      >查询</el-button
    >
    <el-button type="success" icon="el-icon-upload2" style="margin-left: 10px" @click="export1"
      >批量导出</el-button
    >
    <el-button type="danger" icon="el-icon-delete" style="margin-left: 10px" @click="delete1"
      >批量删除</el-button
    >
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column  label="序号" width="120">
        <template slot-scope="scope">
          {{ scope.$index + 1 }} 
        </template>
      </el-table-column>
      <el-table-column prop="unitname" label="单元名称" width="120"> </el-table-column>
      <el-table-column prop="buildnum" label="幢号" show-overflow-tooltip>
        <template slot-scope="scope">
            {{scope.row.buildnum === null? "暂无" : scope.row.buildnum}}
        </template>
      </el-table-column>
      <el-table-column prop="storeynum" label="楼层号" show-overflow-tooltip>
        <template slot-scope="scope">
            {{scope.row.storeynum === null? "暂无" : scope.row.storeynum}}
        </template>
      </el-table-column>
      <el-table-column prop="homenum" label="房号" show-overflow-tooltip>
        <template slot-scope="scope">
            {{scope.row.homenum === null? "暂无" : scope.row.homenum}}
        </template>
      </el-table-column>
      <el-table-column prop="homename" label="住客姓名" show-overflow-tooltip>
        <template slot-scope="scope">
            {{scope.row.homename === null? "暂无" : scope.row.homename}}
        </template>
      </el-table-column>
      <el-table-column prop="homestatus" label="状态" show-overflow-tooltip>
         <template slot-scope="scope">
            {{scope.row.homestatus === null? "未入住" : "已入住"}}
        </template>
      </el-table-column>
      <el-table-column  label="操作" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button  @click="bianji(scope.row)">编辑</el-button>
          <el-button type="danger" @click="back(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
     <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="page"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>
<script>
import * as XLSX from 'xlsx'; // 关键：使用 * as XLSX 确保获取完整的命名空间
import FileSaver from 'file-saver';
export default {

  data() {
    return {
      current:1,
      page:10,
      total:0,
      multipleSelection:[],
      tableData:[],
      value: "",
      input: "",
      input1: "",
      input2: "",
      name: "",
      options: [
        {
          value: "null",
          label: "未入住",
        },
        {
          value: "1",
          label: "已入住",
        },
      ],
      id:"",
      
    };
  },
  methods:{
    toggleSelection(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          this.$refs.multipleTable.clearSelection();
        }
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
    async  indexlist(){
        let res = await this.$axios.get(`http://community.byesame.com/house/gethouseList?currPage=${this.current-1}&pageNum=${this.page}`)
        console.log(res);
        this.tableData = res.data.data
        this.total = res.data.total
        this.id = res.data.data.id
       
      },
       handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.page = val;
        this.current = 1;
        this.indexlist();
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.current = val;
        this.indexlist();
      },
     back(row){
       this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
            let res = await this.$axios.get(`http://community.byesame.com/house/delunitList?id=${row.id}&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjQyMjExMTYxMTQxMTcwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxMzUzMjQ2LCJleHAiOjE3NjE0Mzk2NDZ9.8sAyAtKHQBmE0wU-SIB7SYMJp5fSvzgmJI1ZixWOatE`)
            console.log(res);
            this.indexlist();
            this.$message({
                type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });

        
    },
     bianji(row){
        this.$router.push({
        name: "bian",
        params: { id: row.id },
      });
        
       
        
    },
   async search(){
    let res = await this.$axios.get(`http://community.byesame.com/house/searchnumList?homestatus=${this.value}&unitname=${this.input}&buildnum=${this.input1}&homenum=${this.input2}&homename=${this.name}&currPage=${this.current-1}&pageNum=${this.page}&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjQyMjExMTYxMTQxMTcwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxMzUzMjQ2LCJleHAiOjE3NjE0Mzk2NDZ9.8sAyAtKHQBmE0wU-SIB7SYMJp5fSvzgmJI1ZixWOatE`)
    console.log(res);
    this.tableData = res.data.data
    this.total = res.data.total
   },
   export1(){
      // 1. 处理导出数据
      const exportData = this.tableData.map((row, index) => ({
        '序号': index + 1,
        '单元名称': row.unitname || '暂无',
        '幢号': row.buildnum || '暂无',
        '楼层号': row.storeynum || '暂无',
        '房号': row.homenum || '暂无',
        '住客姓名': row.homename || '暂无',
        '状态': row.homestatus === null ? '未入住' : '已入住'
      }));

      // 2. 创建工作簿和工作表（关键：确保 XLSX.utils 可访问）
      const wb = XLSX.utils.book_new(); // 创建工作簿
      const ws = XLSX.utils.json_to_sheet(exportData, {
        header: ['序号', '单元名称', '幢号', '楼层号', '房号', '住客姓名', '状态']
      });

      // 3. 添加工作表到工作簿
      XLSX.utils.book_append_sheet(wb, ws, '房屋信息表');

      // 4. 生成并下载文件
      const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
      FileSaver.saveAs(blob, '房屋信息批量导出.xlsx');
    },
    async delete1(){
        if (this.multipleSelection.length === 0) {
         this.$alert('请选择要删除的房号信息', '提示', {
          confirmButtonText: '确定',
          
        });
        return;
      }
      
      try {
    // 用 try 包裹确认框，捕获取消操作
    await this.$confirm(
      `此操作将永久删除选中的 ${this.multipleSelection.length} 条记录，是否继续?`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );

    // 用户点击“确定”后，执行删除逻辑
    const ids = this.multipleSelection.map(row => row.id);
    const idParams = ids.map(id => `ids[]=${id}`).join('&');

    const res = await this.$axios.get(
      `http://community.byesame.com/house/delnumList?${idParams}&token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJhZG1pbiIsImVtYWlsIjoiMjQ1MzMxNzM1N0BxcS5jb20iLCJoZWFkIjoiMjAyNTEwMjQyMjExMTYxMTQxMTcwLmpwZyIsInR5cGUiOiIxIiwiaWF0IjoxNzYxMzUzMjQ2LCJleHAiOjE3NjE0Mzk2NDZ9.8sAyAtKHQBmE0wU-SIB7SYMJp5fSvzgmJI1ZixWOatE`
    );

    this.$message({ type: 'success', message: '批量删除成功！' });
    this.indexlist();
    this.$refs.multipleTable.clearSelection();

  } catch (err) {
    // 捕获用户点击“取消”的情况（err 为 "cancel"）
    if (err === 'cancel') {
      this.$message({ type: 'info', message: '已取消批量删除' });
      return; // 终止后续逻辑
    }
    // 其他错误（如接口调用失败）
    this.$message({ type: 'error', message: '批量删除失败，请重试！' });
    console.error('批量删除错误：', err);
  }
    },
  },
    
   
    
    created(){
        this.indexlist();
    }
  }

</script>